<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-button class="filter-item" type="primary" @click="log = true">查看日志</el-button> -->
    </div>
    <el-row :gutter="40" class="panel-group">
      <div v-for="(item, index) in devices" :key="index">
        <!-- 红外 -->
        <el-col v-if="item.tag === 'infrared'" :xs="12" :sm="12" :lg="12" class="dev-col">
          <div :class="item.online === 0 ? 'dev dev-offline' : 'dev'">
            <div class="dev-icon-wrapper card-icon">
              <svg-icon icon-class="peoples" class-name="dev-icon" />
            </div>
            <div class="dev-info">
              <div class="dev-info-name"> {{ item.name }} </div>
              <div class="dev-info-position"> {{ item.position }} </div>
              <div v-if="item.online === 1" class="dev-online"> 在线 </div>
              <div v-else class="dev-offline"> 离线 </div>
            </div>
            <div class="infrared">
              <div v-if="item.status === 1" class="infrared-anybody"> 有人 </div>
              <div v-else-if="item.status === 0" class="infrared-nobody"> 无人 </div>
              <div v-else class="infrared-err"> 无 </div>
            </div>
          </div>
        </el-col>

        <!-- 门禁 -->
        <el-col v-if="item.tag === 'door'" :xs="12" :sm="12" :lg="12" class="dev-col">
          <div :class="item.online === 0 ? 'dev dev-offline' : 'dev'">
            <div class="dev-icon-wrapper card-icon">
              <svg-icon icon-class="door" class-name="dev-icon" />
            </div>
            <div class="dev-info">
              <div class="dev-info-name"> {{ item.name }} </div>
              <div class="dev-info-position"> {{ item.position }} </div>
              <div v-if="item.online === 1" class="dev-online"> 在线 </div>
              <div v-else class="dev-offline"> 离线 </div>
            </div>
            <div class="door">
              <div v-if="item.status === 1" class="door-open"> 开启 </div>
              <div v-else-if="item.status === 0" class="door-close"> 关闭 </div>
              <div v-else class="door-err"> 无 </div>
            </div>
          </div>
        </el-col>

        <!-- 源控开关 -->
        <el-col v-if="item.tag === 'switch'" :xs="12" :sm="12" :lg="12" class="dev-col">
          <div :class="item.online === 0 ? 'dev dev-offline' : 'dev'">
            <div class="dev-icon-wrapper card-icon">
              <svg-icon icon-class="switch" class-name="dev-icon" />
            </div>
            <div class="dev-info">
              <div class="dev-info-name"> {{ item.name }} </div>
              <div class="dev-info-position"> {{ item.position }} </div>
              <div v-if="item.online === 1" class="dev-online"> 在线 </div>
              <div v-else class="dev-offline"> 离线 </div>
            </div>
            <div class="switch">
              <div v-if="item.status === 1" class="switch-open"> 开启 </div>
              <div v-else-if="item.status === 0" class="switch-close"> 关闭 </div>
              <div v-else class="switch-err"> 无 </div>
            </div>
          </div>
        </el-col>

        <!-- 移动平台 -->
        <el-col v-if="item.tag === 'axis'" :xs="24" :sm="24" :lg="24" class="dev-col">
          <div :class="item.online === 0 ? 'dev dev-offline' : 'dev'">
            <div class="dev-icon-wrapper card-icon">
              <svg-icon icon-class="axis" class-name="dev-icon" />
            </div>
            <div class="dev-info">
              <div class="dev-info-name"> {{ item.name }} </div>
              <div class="dev-info-position"> {{ item.position }} </div>
              <div v-if="item.online === 1" class="dev-online"> 在线 </div>
              <div v-else class="dev-offline"> 离线 </div>
            </div>
            <div v-if="item.tag === 'axis'" class="dev-axis">
              <el-button type="success" size="large" @click="AxisEditPositions(item)"> 设置 </el-button>
              <el-button type="primary" size="large" @click="AxisGetPositions(item)"> 获取所有轴位置 </el-button>
              <el-button type="danger" size="large" @click="AxisStop(item)"> 停止所有轴 </el-button>
            </div>
          </div>
          <div :class="item.online === 0 ? 'dev-axis dev-offline' : 'dev-axis'">
            <track-axis :value="item.value" :sub="item.sub" />

          </div>
        </el-col>

        <!-- 圆盘 -->
        <el-col v-if="item.tag === 'circle'" :xs="24" :sm="24" :lg="24" class="dev-col">
          <div :class="item.online === 0 ? 'dev dev-offline' : 'dev'">
            <div class="dev-icon-wrapper card-icon">
              <svg-icon icon-class="axis" class-name="dev-icon" />
            </div>
            <div class="dev-info">
              <div class="dev-info-name"> {{ item.name }} </div>
              <div class="dev-info-position"> {{ item.position }} </div>
              <div v-if="item.online === 1" class="dev-online"> 在线 </div>
              <div v-else class="dev-offline"> 离线 </div>
            </div>
            <div v-if="item.tag === 'circle'" class="dev-axis">
              <el-button type="success" size="large" @click="AxisEditPositions(item)"> 设置 </el-button>
              <el-button type="primary" size="large" @click="AxisGetPositions(item)"> 获取所有轴位置 </el-button>
              <el-button type="danger" size="large" @click="AxisStop(item)"> 停止所有轴 </el-button>
            </div>
          </div>
          <div :class="item.online === 0 ? 'dev-axis dev-offline' : 'dev-axis'">
            <track-axis :value="item.value" :sub="item.sub" />
          </div>
        </el-col>

      </div>
    </el-row>

    <el-drawer
      title="运行日志"
      :visible.sync="log"
      :with-header="false"
      direction="rtl"
      :append-to-body="true"
      size="60%"
    >
      <emqx-log />
    </el-drawer>

    <!-- <el-dialog title="设备信息" :visible.sync="deviceInfoShow"> -->
    <!-- <el-table :data="gridData">
        <el-table-column property="date" label="日期" width="150" />
        <el-table-column property="name" label="姓名" width="200" />
        <el-table-column property="address" label="地址" />
      </el-table> -->
    <!-- </el-dialog> -->

  </div>
</template>

<script>
import { getDevices } from '@/api/device'
import { getAutos } from '@/api/auto'
import { emqxCheckOnline } from '@/api/emqx'
import waves from '@/directive/waves' // waves directive

import TrackAxis from './components/TrackAxis'
// import CircleAxis from './components/CircleAxis'
import EmqxLog from './components/EmqxLog'

import { CMD_INFRARED, CMD_DOOR, CMD_SWITCH, CMD_AXIS, CMD_MOVE, CMD_SYSTEM } from '@/utils/cmd'

export default {
  name: 'XRay',
  components: {
    TrackAxis,
    EmqxLog
  },
  directives: { waves },
  filters: {
    onlineFilter(status) {
      if (status === 1) {
        return '在线'
      } else {
        return '离线'
      }
    }
  },
  data() {
    return {
      task: {},
      value: true,
      log: false,
      tableKey: 0,
      autos: [],
      devicesLoading: false,
      devices: [],
      deviceInfoShow: false,
      status: {
        temperature: 23.5,
        dampness: 23.5,
        pressure: 100
      },
      sourceTimerChecked: false,
      sourceTimerInterval: 0,
      // 轨道
      dialogTrackVisible: false,
      track: {},
      // 圆盘
      dialogCircleVisible: false,
      circle: { axis: [{ start: 10, split_number: 10 }] }
    }
  },
  activated() {
    this.fetchAll()
    // this.checkOnline()
  },
  created() {
    console.log('版本1.0.2~~')
    console.log('版本1.0.2~~')
    console.log('版本1.0.2~~')
    this.doSubscribe()
    // this.checkOnline()
    this.fetchAll()
  },
  methods: {
    fetchAll() {
      // 查询设备在线状态
      emqxCheckOnline().then(response => {
        if (response.code === 200) {
          this.fetchDevices()
        }
      })
    },
    // 查询设备
    fetchDevices() {
      getDevices().then(response => {
        var data = response.data
        if (data === null) {
          data = []
          return false
        }
        for (var i = 0; i < data.length; i++) {
          // 调试用的 device
          data[i].online = 1
          data[i].value = JSON.parse(data[i].value)
          if (data[i].tag === 'door') { data[i].status = -1 }
          if (data[i].tag === 'infrared') { data[i].status = -1 }
          if (data[i].tag === 'switch') { data[i].status = -1 }
          // 坐标初始化赋值
          if (data[i].tag === 'axis') {
            for (var n = 0; n < data[i].value.axis.length; n++) {
              data[i].value.axis[n].position = 'x'
            }
          }
        }
        data.sort(function(a, b) {
          if (a.order === b.order) { // 如果id相同，按照age的降序
            return a.id - b.id
          } else {
            return a.order - b.order
          }
        })
        this.devices = data
        // 获取智能场景
        this.fetchAutos()
        // 获取设备状态
        this.getDeviceStatus()
      })
    },
    fetchAutos() {
      console.log('获取智能场景')
      getAutos().then(response => {
        var data = response.data
        if (data === null) {
          data = []
        } else {
          for (var i = 0; i < data.length; i++) {
            data[i].condition = JSON.parse(data[i].condition)
            data[i].run = JSON.parse(data[i].run)
          }
        }
        this.autos = data
        this.checkAuto()
      })
    },
    // 检查智能场景
    checkAuto() {
      console.log('检测智能场景')
      if (this.devices.length > 0 && this.autos.length > 0) {
        var devices = this.devices
        var data = this.autos
        var msg = ''
        for (var i = 0; i < data.length; i++) {
          // 智能场景使能情况下
          if (data[i].enable === 1) {
            var device = null
            var d = 0
            var conditions = data[i].condition
            var runs = data[i].run
            var c_err_msg = ''
            var isExist = false
            for (var c = 0; c < conditions.length; c++) {
              isExist = false
              for (d = 0; d < devices.length; d++) {
                device = devices[d]
                if (device.sn === conditions[c].sn) {
                  isExist = true
                  if (device.online === 0) {
                    c_err_msg += '<li>场景中的条件：' + '[' + device.name + '(sn:' + device.sn + ')]' + '设备离线</li>'
                    break
                  }
                }
              }
              if (!isExist) {
                c_err_msg += '<li>场景中的条件：' + '[' + conditions[c].name + '(sn:' + conditions[c].sn + ')]' + '设备不存在</li>'
              }
              console.log('条件：' + '[' + conditions[c].name + '(sn:' + conditions[c].sn + ')]' + isExist)
            }
            for (var r = 0; r < runs.length; r++) {
              isExist = false
              for (d = 0; d < devices.length; d++) {
                device = devices[d]
                if (device.sn === runs[r].sn) {
                  isExist = true
                  if (device.online === 0) {
                    c_err_msg += '<li>场景中的动作：' + '[' + device.name + '(sn:' + device.sn + ')]' + '设备离线</li>'
                    break
                  }
                }
              }
              if (!isExist) {
                c_err_msg += '<li>场景中的动作：' + '[' + runs[r].name + '(sn:' + runs[r].sn + ')]' + '设备不存在</li>'
              }
              console.log('动作：' + '[' + runs[r].name + '(sn:' + runs[r].sn + ')]' + isExist)
            }
            if (c_err_msg !== '') {
              msg += '<h4>智能场景：[' + data[i].name + '] 失效, 原因：</h4> ' + c_err_msg + '<br/>'
            }
          }
        }
        if (msg.length === 0) {
          msg = '连锁正常'
          this.$confirm(msg, '提示', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            title: '提示',
            type: 'success'
          })
        } else {
          this.$confirm(msg, '提示', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            title: '提示',
            type: 'warning'
          })
        }
      }
    },

    getDeviceStatus() {
      for (var i = 0; i < this.devices.length; i++) {
        if (this.devices[i].online === 1) {
          if (this.devices[i].tag === 'infrared') {
            // 查询红外设备状态
            this.InfraredGetPeople(this.devices[i])
          }
          if (this.devices[i].tag === 'door') {
            // 查询门禁设备状态
            this.DoorGet(this.devices[i])
          }
          if (this.devices[i].tag === 'switch') {
            // 查询门禁设备状态
            this.SwitchGet(this.devices[i])
          }
          if (this.devices[i].tag === 'axis') {
            // 查询设备位置
            this.AxisGetPositions(this.devices[i])
          }
        }
      }
    },

    // 显示设备信息
    deviceInfo(item) {
      this.deviceInfoShow = true
      console.log(item)
    },

    // 红外获取是否有人
    InfraredGetPeople(item) {
      item.value.people = 0
      var message = {
        code: CMD_INFRARED.get_people.toString(),
        msg: '0'
      }
      this.publish(item.sub, JSON.stringify(message))
    },

    // 门禁获取是否开启
    DoorGet(item) {
      item.value.door = 0
      this.publish(item.sub, JSON.stringify({
        code: CMD_DOOR.get_door.toString(),
        msg: '0'
      }))
    },

    // 源控获取状态
    SwitchGet(item) {
      item.value.switch = 0
      this.publish(item.sub, JSON.stringify({
        code: CMD_SWITCH.get_switch.toString(),
        msg: '0'
      }))
    },

    // 停止所有轴运动
    AxisStop(item) {
      this.publish(item.sub, JSON.stringify({
        code: CMD_MOVE.stop.toString(),
        msg: '0'
      }))
    },

    // 获取所有轴位置
    AxisGetPositions(item) {
      console.log('移动轴获取位置...')
      this.publish(item.sub, JSON.stringify({
        code: CMD_MOVE.get_positions.toString(),
        msg: '1'
      }))
    },

    AxisEditPositions(item) {
      console.log('编辑运动轴设备...')
      this.$router.push({ path: '/editor/device/axis/set', query: item })
    },

    // axis轴运动处理
    axisDeal(device, aswcode, aswmsg) {
      for (var i = 0; i < CMD_AXIS.length; i++) {
        if (CMD_AXIS[i].set_position === aswcode) {
          this.$message({ message: '[' + device.name + ']-' + '[' + device.value.axis[i].name + ']' + '重置位置成功', type: 'success' })
          // this.publish(device.sub, JSON.stringify({ code: CMD_AXIS[i].get_position.toString(), msg: '1' }))
        }
        if (CMD_AXIS[i].move_pos === aswcode) {
          this.$message({ message: '[' + device.name + ']-' + '[' + device.value.axis[i].name + ']' + '开始移动', type: 'success' })
          break
        }
        if (CMD_AXIS[i].get_status === aswcode) {
          device.value.axis[i].status = parseInt(aswmsg)
          // if (device.value.axis[i].status === 0) {
          //   device.value.axis[i].status = 3
          // }
          // this.$message({ message: '[' + device.name + ']-' + '[' + device.value.axis[i].name + ']' + '状态发生变化', type: 'success' })
          break
        }
        if (CMD_AXIS[i].get_position === aswcode) {
          // 下面传上来是um, 位置转换为mm, 系数为1000
          var position = parseFloat(aswmsg) / 1000
          // 更新位置
          device.value.axis[i].position = position
          // 比对当前位置和预设位置, 到达指定位置后显示位置名称
          var positions = device.value.axis[i].positions
          var isArrived = false
          for (var p = 0; p < positions.length; p++) {
            var err = Math.abs(position - parseFloat(positions[p].value))
            // console.log('运动err:' + err)
            // var thresh = 200 / 1000
            if (err < 0.2) {
              device.value.axis[i].position_name = positions[p].name
              console.log('运动到预设指定位置：' + positions[p].name)
              isArrived = true
              break
            }
          }
          if (isArrived) {
            this.$message({
              message: '[' + device.name + ']->' + '(' + device.value.axis[i].name + ')' + '已移动到预设位置：' + '[' + device.value.axis[i].position_name + '] >>>' + device.value.axis[i].position,
              type: 'success'
            })
          } else {
            device.value.axis[i].position_name = '无'
            this.$message({
              message: '[' + device.name + ']->' + '(' + device.value.axis[i].name + ')' + '移动到位置:' + device.value.axis[i].position,
              type: 'success',
              duration: 500
            })
          }
          // 有任务时
          if (this.task.done === false) {
            this.task.once_done = true
          }
          break
        }
      }
    },

    // mqtt相关操作
    doSubscribe() {
      this.subscribe('fsc/#')
      // this.subscribe('fsc/online')
      // var data = this.devices
      // for (var i = 0; i < data.length; i++) {
      //   this.subscribe(data[i].pub)
      // }
    },

    subscribe(val) {
      console.log('订阅主题')
      console.log(val)
      this.$mqtt.subscribe(val)
    },
    publish(topic, message) {
      console.log('>>>>>>>>>>>>>推送消息')
      console.log('topic:' + topic)
      console.log('message:' + message)
      this.$mqtt.publish(topic, message)
    }
  },
  mqtt: {
    '#'(data, topic) {
      console.log('<<<<<<<<<<<<<<收到消息')
      console.log('topic:' + topic)
      console.log('payload: ' + String.fromCharCode.apply(null, data))
      try {
        var info = JSON.parse(data)
        var aswcode = parseInt(info.aswcode)
        var aswmsg = info.aswmsg
        var i = 0
        for (i = 0; i < this.devices.length; i++) {
          var device = this.devices[i]
          if (aswcode === CMD_SYSTEM.online) {
            if (device.sn === info.clientid) {
              this.$message({ message: '[' + device.name + ']-' + '在线状态变化', type: 'error' })
              device.online = parseInt(info.aswmsg)
            }
          }
          // 设备离线，不处理状态变化
          if (device.online === 0) {
            continue
          }
          if (device.pub === topic) {
            // 红外
            if (device.tag === 'infrared') {
              if (aswcode === CMD_INFRARED.get_people) {
                this.$message({ message: '[' + device.name + ']-' + '变化', type: 'warning' })
                device.status = parseInt(aswmsg)
              }
            }
            if (device.tag === 'door') {
              if (aswcode === CMD_DOOR.get_door) {
                this.$message({ message: '[' + device.name + ']-' + '变化', type: 'warning' })
                device.status = parseInt(aswmsg)
              }
            }
            if (device.tag === 'switch') {
              if (aswcode === CMD_SWITCH.get_switch) {
                this.$message({ message: '[' + device.name + ']-' + '变化', type: 'error' })
                device.status = parseInt(aswmsg)
              }
            }
            // 轨道数据处理
            if (device.tag === 'axis') {
              console.log('轨道数据处理')
              this.axisDeal(device, aswcode, aswmsg)
            }
          }
        }
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.panel-group {
  margin-top: 18px;

  .dev-offline {
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: grayscale(100%);
    filter: gray;
  }

  .dev-col {
    margin-bottom: 15px;
  }
  .dev-axis {
    height: 100%;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
    border-color: rgba(0, 0, 0, .05);
  }

  .dev {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 8px 8px 40px rgba(0, 0, 0, .05);
    border-color: rgba(0, 0, 0, .05);

    &:hover {
      .dev-icon-wrapper {
        color: #fff;
      }

      .card-icon{
        background: #40c9c6;
      }
    }

    .dev-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
      color: #40c9c6;
    }

    .dev-icon {
      float: left;
      font-size: 48px;
    }

    .infrared {
      float: right;
      font-weight: bold;
      margin: 16px;
      margin-left: 0px;
      .infrared-anybody {
        line-height: 40px;
        color: rgba(250, 0, 0, 0.45);
        font-size: 40px;
        margin-bottom: 12px;
      }
      .infrared-nobody {
        line-height: 48px;
        color: rgba(0, 250, 0, 0.45);
        font-size: 40px;
        margin-bottom: 12px;
      }
      .infrared-err {
        line-height: 48px;
        color: gray;
        font-size: 40px;
        margin-bottom: 12px;
      }
    }
    .door {
      float: right;
      font-weight: bold;
      margin: 16px;
      margin-left: 0px;
      .door-open {
        line-height: 48px;
        color: rgba(250, 0, 0, 0.45);
        font-size: 40px;
        margin-bottom: 12px;
      }
      .door-close {
        line-height: 48px;
        color: rgba(0, 250, 0, 0.45);
        font-size: 40px;
        margin-bottom: 12px;
      }
      .door-err {
        line-height: 48px;
        color: gray;
        font-size: 40px;
        margin-bottom: 12px;
      }
    }

    .switch {
      float: right;
      font-weight: bold;
      margin: 16px;
      margin-left: 0px;
      .switch-open {
        line-height: 48px;
        color: rgba(250, 0, 0, 0.45);
        font-size: 40px;
        margin-bottom: 12px;
      }
      .switch-close {
        line-height: 48px;
        color: rgba(0, 250, 0, 0.45);
        font-size: 40px;
        margin-bottom: 12px;
      }
      .switch-err {
        line-height: 48px;
        color: gray;
        font-size: 40px;
        margin-bottom: 12px;
      }
    }

    .dev-axis {
      float: right;
      font-weight: bold;
      margin: 16px;
      margin-left: 10px;
      .dev-status {
        line-height: 18px;
        color: rgba(250, 0, 0, 0.45);
        font-size: 32px;
        margin-bottom: 12px;
      }
    }

    .dev-info {
      float: left;
      font-weight: bold;
      margin: 26px;
      margin-left: 10px;

      .dev-info-name {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 20px;
        margin-bottom: 12px;
      }
      .dev-info-position {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .dev-online {
        line-height: 18px;
        color: rgba(0, 255, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .dev-offline {
        line-height: 18px;
        color: rgba(255, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

    }
  }
}

@media (max-width:550px) {
  .dev-info {
    display: none;
  }

  .dev-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>
